package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Item;
import model.User;
import dao.ItemManager;
import dao.UserManager;
import dao.Utils;

/**
 * Servlet implementation class BorrowItemServlet
 */
@WebServlet("/borrowItem")
public class BorrowItemServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private ItemManager manager;

    @Override
    public void init(ServletConfig config) throws ServletException
    {
	super.init(config);
	this.manager = new ItemManager();
    }

    @Override
    public void destroy()
    {
	this.manager = null;
	super.destroy();
    }

    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException
    {
	HttpSession session = request.getSession(true);
	Item item = (Item) session.getAttribute("item");
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	String expectedRetunDate = request.getParameter("expectedReturnDate");
	User user = UserManager.getUser(username, password);
	if (item != null && user != null)
	{
	    boolean result = false;
	    boolean isValidDate = Utils.validateReturnDate(expectedRetunDate,
		    item.getMaxPeriod());

	    if (isValidDate)
	    {

		try
		{
		    result = manager.borrowItem(item.getId(),
			    user.getUsername(), expectedRetunDate);
		}
		catch (SQLException e)
		{
		    System.err.println(e.getMessage());
		}
		String message = "";
		if (result)
		{
		    message = "Item borrowed successfully.";

		} else
		{
		    message = "A database error occurred.";
		}
		session.setAttribute("message", message);

	    }
	    response.sendRedirect("items.jsp");
	}
    }
}
